package cn.daniellee.plugin.map;

import cn.daniellee.plugin.QrcodeMap;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.map.MapView;
import org.bukkit.plugin.java.JavaPlugin;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

public class MapGenerator {

	private static ItemStack mapItem = null;

	private static Material material = Material.MAP;

	static {
		String name = Bukkit.getServer().getClass().getName();
		name = name.substring(name.indexOf("craftbukkit.") + "craftbukkit.".length());
		name = name.substring(0, name.indexOf("."));
		StringBuilder sb = new StringBuilder();
		for (int i = 3; i < 10; i++) {
			if ((name.charAt(i) == '_') || (name.charAt(i) == '.')) {
				break;
			}
			sb.append(name.charAt(i));
		}
		if (Integer.valueOf(sb.toString()) > 12) material = Material.FILLED_MAP;
	}

	public static void give(Player player) {
		if (mapItem != null) {
			HashMap<Integer, ItemStack> leftItems = player.getInventory().addItem(mapItem);
			if(leftItems.isEmpty()){
				player.sendMessage((QrcodeMap.prefix + QrcodeMap.config.getString("give-success")).replace("&", "§"));
			} else {
				player.sendMessage((QrcodeMap.prefix + QrcodeMap.config.getString("inventory-full")).replace("&", "§"));
			}
		} else {
			player.sendMessage((QrcodeMap.prefix + QrcodeMap.config.getString("initialize-failed")).replace("&", "§"));
		}
	}

	public static boolean initialize(JavaPlugin plugin, String link) {
		mapItem = null;
		BufferedImage image;
		try {
			URL url = new URL("http://qr.liantu.com/api.php?w=128&m=3&text=" + link);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(5000);
			InputStream stream = connection.getInputStream();
			image = ImageIO.read(stream);
			if (image != null) {
				MapView map = Bukkit.createMap(Bukkit.getWorlds().get(0));
				map.getRenderers().forEach(item -> map.removeRenderer(item));
				map.addRenderer(new QrcodeRenderer(image, QrcodeRenderer.TICK_FOR_STILLS));
				ItemStack item = new ItemStack(material, 1, (short) map.getId());
				ItemMeta itemMeta = item.getItemMeta();
				itemMeta.setDisplayName(QrcodeMap.config.getString("name").replace("&", "§"));
				List<String> loreList = QrcodeMap.config.getStringList("lore");
				loreList.forEach(lore -> lore = lore.replace("&", "§"));
				itemMeta.setLore(loreList);
				item.setItemMeta(itemMeta);
				mapItem = item;
				plugin.getLogger().info(QrcodeMap.config.getString("image-load-success"));
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		plugin.getLogger().info(QrcodeMap.config.getString("image-load-failed"));
		return false;
	}

}
